package cup.common.config;

import cup.core.boot.config.CupExecutorConfiguration;
import cup.core.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : ruoyu
 * @date : 2022/3/3
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {


	private final CupExecutorConfiguration cupExecutorConfiguration;

	@Autowired
	public GlobalExceptionHandler(CupExecutorConfiguration cupExecutorConfiguration) {
		this.cupExecutorConfiguration = cupExecutorConfiguration;
	}


	/**
	 * 全局异常捕捉返回 兼容处理原有错误日志逻辑
	 */
	@ExceptionHandler(Exception.class)
	public ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable e) {
		//正常打印错误日志
		e.printStackTrace();
		log.error("错误:[{}]", e.getMessage(), e);
		try {
			cupExecutorConfiguration.getAsyncUncaughtExceptionHandler().handleUncaughtException(e, null, null);
		} catch (Exception ee) {
			ee.printStackTrace();
			throw ee;
		}
		return new ResponseEntity<R>(R.fail(e.getMessage()), HttpStatus.OK);
	}
}
